package com.jplus.mvc.action.api.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.anno.com.Autowired;
import com.jplus.core.anno.com.Service;
import com.jplus.core.utill.JSON.JSONObject;
import com.jplus.mvc.action.api.bean.IDCardOCRVo;
import com.jplus.mvc.action.api.bean.SysIDCard;
import com.jplus.mvc.action.api.db.DBStore;
import com.jplus.mvc.action.api.kit.Global;
import com.jplus.mvc.action.api.kit.IDCardKit.IDCard;
import com.jplus.mvc.action.api.kit.IDCardKit.STATUS;
import com.jplus.mvc.action.api.third.AliyunApi;
import com.jplus.mvc.action.api.third.BaiduApi;
import com.jplus.mvc.util.Base64Util;

@Service
public class CommonService {
	private final Logger log = LoggerFactory.getLogger(CommonService.class);
	private @Autowired BaiduApi baidu;
	private @Autowired AliyunApi aliyun;
	private @Autowired DBStore dBStore;
	private @Autowired Global global;

	/**
	 * 身份证卡OCR
	 */
	public IDCardOCRVo cardOcr(String image) {
		try {
			// == BaiduAPI =================================================
			JSONObject jobj = baidu.idcardOCR(image, true);
			IDCardOCRVo vo = new IDCardOCRVo(getC(jobj, "姓名"), getC(jobj, "民族"), getC(jobj, "住址"), getC(jobj, "公民身份号码"),
					getC(jobj, "出生"), getC(jobj, "性别"));
			// == SaveIMG ==================================================
			global.saveCardImg(vo.cardNo + ".jpg", Base64Util.decode(image));// 异步执行
			return vo;
		} catch (Exception e) {
			log.error("CardOCR ERROR:", e);
			return null;
		}
	}

	private String getC(JSONObject obj, String key) {
		return obj.getJSONObject("words_result").getJSONObject(key).getString("words");
	}

	/**
	 * 银行卡OCR
	 */
	public String bankOcr(String image) {
		try {
			// == BaiduAPI =================================================
			JSONObject jobj = baidu.bankcardOCR(image).getJSONObject("result");
			return jobj.getString("bank_card_number");
		} catch (Exception e) {
			log.error("CardOCR ERROR:", e);
			return null;
		}
	}

	/**
	 * 二要素实名认证
	 */
	public boolean authenCard(String cardNo, String name) {
		cardNo = cardNo.trim();
		name = name.trim();
		// 1.基础校验通过
		IDCard card = Global.IDCARDKIT.doCheck(cardNo);
		if (card.status == STATUS.SUCC) {
			// 1.查询本地库
			SysIDCard sic = dBStore.getIDCard(cardNo);
			if (sic != null && name.equals(sic.card_name))
				return true;
			// 1.查询API
			boolean bo = aliyun.idCardAuth(cardNo, name);
			if (bo)
				dBStore.addIDCard(new SysIDCard(cardNo, name, Integer.valueOf(card.areaCode),
						card.sex.equals("男") ? 1 : 0, Integer.valueOf(card.birthday))); // 保存入库
			return bo;
		}
		return false;
	}

}
